import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import route from '@/router'

// 创建一个axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 向请求url前拼接
  // withCredentials: true, // 当跨域请求时发送cookie
  timeout: 10000 // 	请求超时毫秒
})

// 请求拦截器
service.interceptors.request.use(
  config => {
		const token = localStorage.setItem('juehm_token')
    if (token) config.headers.Authorization = token
    return config
  },
  error => {
    // 请求错误处理
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 0) {
      return res.data
    } else if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
      // 重新登陆
      MessageBox.confirm('您已经登出，您可以取消停留在此页面，或再次登录', '确认注销', {
        confirmButtonText: '重新登陆',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
				localStorage.removeItem('juehm_token')
				route.push('/login')
      })
    } else {
      const err = new Error(res.message || '服务器开小差啦~')
      err.code = res.code
      err.message = res.message
      return Promise.reject(err)
    }
  },
  error => {
		// 响应错误处理
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 3000
    })
    return Promise.reject(error)
  }
)

export const get = (url, params)=> service.get({url, params})

export const post = (url, data)=> service.post({url, data})
